# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from .models import Log
import re
import os
import subprocess
import datetime


def run(project_dir, date_from, date_to, search_key, filename):
    log_dic = {}
    branch_dic = {}
    try:
        os.chdir(project_dir)
    except Exception, e:
        raise e
    branches_list = []
    branches_list = get_branches()
    for branch in branches_list:
        branch_dic = deal_branch(date_from, date_to, branch, search_key)
        for item in branch_dic:
            if item not in log_dic:
                log_dic[item] = branch_dic[item]
            else:
                log_dic[item] += branch_dic[item]
    # log_output(filename, log_dic)


# get all branches of a project
def get_branches():
    branch_list = []
    branches = []
    tmp_str = ''
    try:
        cmd_git_remote = 'git remote show origin'
        proc = subprocess.Popen(cmd_git_remote.split(),
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        stdout, stderr = proc.communicate()
        tmp_str = stdout.split('Local branches configured')[0]
        try:
            tmp_str = tmp_str.split('Remote branches:\n')[1]
        except:
            tmp_str = tmp_str.split('Remote branch:\n')[1]
        branches = tmp_str.split('\n')
        for branch in branches[0:-1]:
            if re.search(' tracked', branch) is not None:
                branch = branch.replace('tracked', '').strip(' ')
                branch_list.append(branch)
    except Exception, error:
        if branch_list == []:
            print "Can not get any branch!"
    return branch_list


# abstract log of one branch
def deal_branch(date_from, date_to, branch, search_key):
    try:
        # os.system('git checkout ' + branch)
        # os.system('git pull ')
        # os.system('git log ')
        print('*****deal_branch*****')
    except Exception, error:
        print error
    cmd_git_log = ["git",
                   "log",
                   "--stat",
                   "--no-merges",
                   "-m",
                   "--after="+date_from,
                   "--before="+date_to]
    proc = subprocess.Popen(cmd_git_log,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    branch_dic = deal_lines(date_from,
                                date_to,
                                search_key,
                                stdout)
    return branch_dic


# analyze log
def deal_lines(date_from, date_to, search_key, stdout):

    srt = stdout.replace('commit', 'cut commit')
    for line in srt.split('cut '):
        commit_dic = {}
        author_dic = {}
        date_dic = {}
        fc_num_dic = {}
        insert_dic = {}
        delete_dic = {}
        dic = {}
        # 获取版本号
        if re.search('commit ', line) is not None:
            commit_id = line.split('commit ')[1].split('\n')[0]
            if commit_id not in commit_dic:
                dic['commit'] = [commit_id]
            else:
                dic['commit'] += [commit_id]
        # 获取作者信息
        if re.search('Author: ', line) is not None:
            author = line.split('Author: ')[1].split('\n')[0]
            if author not in author_dic:
                dic['author'] = [author]
            else:
                dic['author'] += [author]
        # 获取日期信息
        if re.search('Date: ', line) is not None:
            date = line.split('Date:   ')[1].split(' +')[0]
            if date not in date_dic:
                dic['date'] = [date]
            else:
                dic['date'] += [date]
        # 获取修改被文件数量信息
        if re.search('file change', line) is not None:
            change_str = line.split('\n\n')[2].split('\n\n')[0]
            fc_num = change_str.split('\n')[1].split('file changed,')[0]
            if fc_num not in fc_num_dic:
                dic['file_changed'] = [fc_num]
            else:
                dic['file_changed'] += [fc_num]
        # 获取新增行数信息
        if re.search('insertions', line) is not None:
            change_str = line.split('\n\n')[2].split('\n\n')[0]
            insert_num = change_str.split('file changed, ')[1].split('insertions(+)')[0]
            if insert_num not in insert_dic:
                dic['insertions'] = [insert_num]
            else:
                dic['insertions'] += [insert_num]
        # 获取删除行数信息
        if re.search('deletions', line) is not None:
            change_str = line.split('\n\n')[2].split('\n\n')[0]
            delete_num = change_str.split('insertions(+), ')[1].split('deletions(-)')[0]
            if delete_num not in delete_dic:
                dic['deletions'] = [delete_num]
            else:
                dic['deletions'] += [delete_num]
        if dic.get('commit'):
            try:
                a = Log()
                commit = ''.join(dic.get('commit', "not found"))
                a.commit = commit
                author = ''.join(dic.get('author', "not found"))
                a.author = author
                date0 = ''.join(dic.get('date'))
                date = datetime.datetime.strptime(date0, "%a %b %d %H:%M:%S %Y").date()
                a.datetime = date
                a.files = int(''.join(dic.get('file_changed', "0")))
                a.add = int(''.join(dic.get('insertions', "0")))
                a.remove = int(''.join(dic.get('deletions', "0")))

                a.save()
            except Exception:
                return HttpResponse("!!!!!")
        else:
            continue
    return HttpResponse("success")
    # return date_dic

'''
# write commits log to file
def log_output(filename, log_dic):
    fi = open(filename, 'w')
    for item in log_dic:
        print('!!!!!')
        m1 = '--'*5 + 'Date:' + item + '--'*20 + '\n'
        fi.write(m1)
    fi.close()
'''


# if __name__ == '__main__':
def start(request):
    # path of the .git project. example: "/home/username/projects/jekyll_vincent"
    project_dir = "D:\gitProject"
    date_from = "2015-11-23"
    date_to = "2015-11-25"
    # only search 'Bug: \d+' for default
    search_key = ""
    # name of output file. example:"/home/username/jekyll_0125_0226.log"
    filename = "C:\Users\Administrator\Desktop\git.log"
    run(project_dir, date_from, date_to, search_key, filename)